package com.yimils.core.goods.serivce.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yimils.core.goods.dto.PersonAddReq;
import com.yimils.core.goods.dto.PersonUpdateReq;
import com.yimils.core.goods.entity.PersonEntity;
import com.yimils.core.goods.mapper.PersonMapper;
import com.yimils.core.goods.serivce.PersonService;
import com.yimils.core.goods.vo.PersonRes;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service("personService")
public class PersonServiceImpl extends ServiceImpl<PersonMapper, PersonEntity> implements PersonService {
    @Override
    public Boolean savePerson(PersonAddReq personAddReq) {
        PersonEntity personEntity = new PersonEntity();
        personEntity.setRightPersonName(personAddReq.getRightPersonName());
        personEntity.setState(Boolean.FALSE);
        personEntity.setCreateTime(LocalDateTime.now());
        personEntity.setUpdateTime(LocalDateTime.now());
        return save(personEntity);
    }

    @Override
    public Boolean updatePerson(PersonUpdateReq personUpdateReq) {
        QueryWrapper<PersonEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(PersonEntity::getId, personUpdateReq.getPersonId()).eq(PersonEntity::getState, Boolean.FALSE);
        PersonEntity entity = getOne(qw);
        entity.setRightPersonName(personUpdateReq.getRightPersonName());
        entity.setUpdateTime(LocalDateTime.now());
        return saveOrUpdate(entity);
    }

    @Override
    public Boolean deletePerson(List<Long> personIds) {

        QueryWrapper<PersonEntity> qw = new QueryWrapper<>();
        qw.lambda().in(PersonEntity::getId, personIds).eq(PersonEntity::getState, Boolean.FALSE);
        List<PersonEntity> entities = list(qw);
        entities.forEach(o -> {
            o.setState(Boolean.TRUE);
            o.setUpdateTime(LocalDateTime.now());
        });
        return saveOrUpdateBatch(entities);
    }

    @Override
    public List<PersonRes> listPerson() {
        QueryWrapper<PersonEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(PersonEntity::getState, Boolean.FALSE);
        List<PersonEntity> entities = list(qw);
        return entities.stream().map(o -> {
            PersonRes personRes = new PersonRes();
            personRes.setPersonId(o.getId());
            personRes.setRightPersonName(o.getRightPersonName());
            return personRes;
        }).collect(Collectors.toList());
    }

    @Override
    public List<PersonEntity> listPerson(List<Long> personIds) {
        QueryWrapper<PersonEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(PersonEntity::getId, personIds).eq(PersonEntity::getState, Boolean.FALSE);
        return list(qw);
    }
}
